<?php

namespace addons\order\utils;

use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class WechatPay {

    protected $config = [
        'appid' => '', // APP APPID
        'app_id' => '', // 公众号 APPID
        // 'miniapp_id' => 'wxb3fxxxxxxxxxxx', // 小程序 APPID
        'mch_id' => '',
        'key' => '',
        'notify_url' => '/api/Notify/WechatNotify',
        'cert_client' => './cert/apiclient_cert.pem', // optional，退款等情况时用到
        'cert_key' => './cert/apiclient_key.pem',// optional，退款等情况时用到
        'log' => [ // optional
            'file' => './logs/wechat.log',
            'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
        'mode' => 'normal', // optional, dev/hk;当为 `hk` 时，为香港 gateway。
    ];

    public function __construct(){
        $config = config('wechat');
        $url = config('base_url');
        $this->config['appid']  = $config['app_id'];
        $this->config['app_id']  = $config['app_id'];
        $this->config['key']  = $config['pay_secret'];
        $this->config['mch_id']  = $config['mch_id'];
        $this->config['notify_url']  = $url.$this->config['notify_url'];

    }

    public function pay($out_trade_no,$total_fee,$body){
        $total_fee = (int)bcmul($total_fee,100,1);
        $order = [
            'out_trade_no' => $out_trade_no,
            'total_fee' => $total_fee, // **单位：分**
            'body' => $body,
        ];

        $pay = Pay::wechat($this->config)->app($order);
        return $pay->getContent();
    }

    /**
     * 异步处理
     */
    public function notify(){
        $pay = Pay::wechat($this->config);
        try{
            $data = $pay->verify(); // 是的，验签就这么简单！
            if($data){
                $orderM = new \addons\order\model\OrderCms();
                $orderM->startTrans();
                $we_data = $data->all();
                $we_data['pay_type'] = 'wechat';
                $res = $orderM->paySuccess($we_data);
                if($res){
                    //支付成功发送短信
                    $MemberBalanceM = new \addons\member\model\Balance();
                    $coin_type = 2;
                    $amount = $res['inter_amount'];
                    $res2 = $MemberBalanceM->updateBalance($res['user_id'], $coin_type, $amount,1);
                    if(!$res2){
                        $orderM->rollback();
                        return false;
                    }
                    $TradingRecordM = new \addons\member\model\TradingRecord();
                    $res = $TradingRecordM->addRecord($res['user_id'], $amount, $res2['before_amount'], $res2['amount'], $coin_type, 100, 1, $res['user_id'], '用户微信充值');
                    if(!$res){
                        $orderM->rollback();
                        return false;
                    }
                    $orderM->commit();
                    return $pay->success()->send();
                }else{
                    $orderM->rollback();
                    return false;
                }
            }
            Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            Log::debug('Wechat error', $e->getMessage());
            return false;
            // $e->getMessage();
        }
        // return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }


    /**
     * 退款
     */
    public function refund($out_trade_no,$total_fee,$refund_desc='测试退款haha'){
        $total_fee = (int)bcmul($total_fee,100,1);
        $order = [
            'out_trade_no' => $out_trade_no,
            'out_refund_no' => time(),
            'total_fee' => $total_fee,
            'refund_fee' => $total_fee,
            'refund_desc' => $refund_desc,
        ];
        $pay = Pay::wechat($this->config);
        $res = $pay->refund($order);
        // var_dump($res);
        // var_dump($res->all());
        return $res->all();
    }


    

}